import 'package:flutter/material.dart';

/// @Date 2024/12/05 17:02
/// @author chris
/// @desc change notifier demo
///

class TestChangeNotifier extends StatefulWidget {
  const TestChangeNotifier({super.key});

  @override
  State<TestChangeNotifier> createState() => _TestChangeNotifierState();
}

class _TestChangeNotifierState extends State<TestChangeNotifier> {
  final counterCtrl = CounterCtrl();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          "test changenotifier",
        ),
      ),
      body: Column(
        children: [
          ListenableBuilder(
            listenable: counterCtrl,
            builder: (ctx, child) => Text("${counterCtrl.count}"),
          ),
          ElevatedButton(
            onPressed: () {
              counterCtrl.count++;
            },
            child: Text("+"),
          ),
        ],
      ),
    );
  }
}

class CounterCtrl extends ChangeNotifier {
  // 构造函数，允许传入默认值
  CounterCtrl({int initialCount = 0}) : _count = initialCount;

  int _count = 0;

  get count => _count;

  /// 在set值的时候，调用notifyListeners 更新组件的监听关系
  set count(val) {
    _count = val;
    notifyListeners();
  }
}
